#include "sql.hpp"
#include <func.h>
#include<string>

DataBase::DataBase(string tablename)
    : TableName(tablename)
{
    sqlObj = mysql_init(nullptr);
    MysqlConnectInfo info;
    MysqlInfoInit(&info, sqlObj);
    auto ret = mysql_real_connect(info.mysql,
                                  info.host,
                                  info.user,
                                  info.password,
                                  info.db,
                                  info.port,
                                  info.unix_socket,
                                  info.client_flag);
    if (!ret)
        printf("mysql connect faild\n");
    else
        printf("mysql connect success\n");
}
DataBase::~DataBase()
{
}

// 初始化要连接的数据库信息
int DataBase::MysqlInfoInit(MysqlConnectInfo *mysqlconnectInfo, MYSQL *mysql)
{
    memset(mysqlconnectInfo, 0, sizeof(MysqlConnectInfo));
    mysqlconnectInfo->mysql = mysql;
    memcpy(mysqlconnectInfo->host, "localhost", 9);
    memcpy(mysqlconnectInfo->user, "root", 4);
    // 将457260245更改为自己的mysql的root密码  后面的9改为自己的密码长度
    memcpy(mysqlconnectInfo->password, "457260245", 9);
    memcpy(mysqlconnectInfo->db, "study", 9);
    mysqlconnectInfo->unix_socket = NULL;
    // memcpy(mysqlconnectInfo->unix_socket,"",1);
    return 0;
}

//  查询表是否存在
bool DataBase::InquireTable(string tableName)
{
    string buf = ("show tables like '" + tableName + "';");
    auto ret = mysql_query(this->sqlObj, buf.c_str());
    if(ret == 0)
    {
        printf("inquire success\n");
    }
    else 
    {
        printf("inquire faild\n");
    }
    MYSQL_RES *res = mysql_store_result(this->sqlObj);
    int rows = mysql_num_rows(res);    
    if(rows == 1)
    {
        printf("table %s exist\n",tableName.c_str());
        return true;
    }
    printf("table %s is NOT exist\n",tableName.c_str());
    return false;
}

//  创建表
bool DataBase::CreateTable(string tableName)
{
    string buf = ("CREATE TABLE " + tableName + " (id INT PRIMARY KEY,name VARBINARY(20));");
    auto ret = mysql_query(this->sqlObj, buf.c_str());
    if(ret == 0)
    {
        printf("create success\n");
        return true;
    }
    else 
    {
        printf("create faild\n");
        return false;
    }
}

// 向表中插入数据
bool DataBase::InsertData(string tableName,int id,string name)
{
    char buf[1024] = {0};
    sprintf(buf,"insert into %s values (%d,'%s');",tableName.c_str(),id,name.c_str());
    auto ret = mysql_query(this->sqlObj, buf);
    if(ret == 0)
    {
        //printf("insert success\n");
        return true;
    }
    else 
    {
        //printf("insert faild\n");
        return false;
    }
}